package com.framework.util;

import com.framework.exception.BizException;
import com.framework.thread.ReqComHold;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class LocLockUtil {

    private static Cache<String, Boolean> locLock = CacheBuilder.newBuilder()
            .expireAfterAccess(30, TimeUnit.SECONDS).build();

    /**
     *
     * @param key
     * @return
     */
    public static Boolean lock(String key) throws BizException {
        Boolean flag = false;
        for(int i = 0; i < 3; i++){
            flag = get(key);
            if(!flag){
                break;
            }
            try {
                Thread.sleep(i+2);
            } catch (InterruptedException e) {
                log.error("lock wait err", e);
            }
        }
        if(flag){
            throw new BizException("lock fail", new Throwable("LocLockUtil lock fail, key:"+ key));
        }
        locLock.put(key, true);
        return true;
    }

    public static void unLock(String key){
        locLock.put(key, false);
    }

    public static Boolean get(String key){
        try {
            return locLock.get(key, () -> false);
        }catch (Exception e){
            log.error("loc lock get fail",e);
        }
        return false;
    }

    /**
     * get lock key by group with userid
     * @param group
     * @return
     */
    public static String buildKey(String group){
        return group + ReqComHold.getReqCom().getUserId();
    }

}
